package com.engine.demo.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.sw.duban.util.LogTool;
import com.cloudstore.dev.api.util.Util_TableMap;
import com.cloudstore.eccom.core.WeaCommon;
import com.weaverboot.frame.ioc.anno.classAnno.WeaIocComponent;
import com.weaverboot.frame.ioc.anno.classAnno.WeaIocReplaceComponent;
import com.weaverboot.frame.ioc.anno.methodAnno.WeaReplaceAfter;
import com.weaverboot.frame.ioc.anno.methodAnno.WeaReplaceBefore;
import com.weaverboot.frame.ioc.handler.replace.weaReplaceParam.impl.WeaAfterReplaceParam;
import com.weaverboot.frame.ioc.handler.replace.weaReplaceParam.impl.WeaBeforeReplaceParam;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import org.xml.sax.InputSource;
import weaver.conn.RecordSet;
import weaver.general.Util;

import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;

@WeaIocReplaceComponent
public class demo01 {
    private final static LogTool log = new LogTool("/log/assetlog/weareplacebefore",false);
    @WeaReplaceBefore(value = "/api/public/browser/data/17", order = 1, description = "haha")
    public String setParam2(WeaBeforeReplaceParam param){

        Map paraMap=param.getParamMap();
        String subid =Util.null2String(paraMap.get("zcsubid")).trim() ;
        String type=Util.null2String(paraMap.get("type")).trim() ;
        String cmd=Util.null2String(paraMap.get("cmd")).trim();
        if(("search".equals(cmd)||"newly".equals(cmd))&&!"".equals(subid)){
            paraMap.put("subcompanyid",subid);
            param.setParamMap(paraMap);
            String urlnew=param.getApiUrl();
            //param.getRequest().setAttribute("subcompanyid",subid);
            param.getRequest().getSession().setAttribute("subcompanyid",subid);
        }
        return "";
    }
    @WeaReplaceAfter(value = "/api/public/browser/data/17", order = 1, description = "haha")
    public String setParam(WeaAfterReplaceParam param){
        Map paraMap=param.getParamMap();
        String demo =param.getData();
        String cmd=Util.null2String(paraMap.get("cmd")).trim() ;
        String subid =Util.null2String(paraMap.get("zcsubid")).trim() ;
        String type=Util.null2String(paraMap.get("type")).trim() ;
        String newDemo=demo;
        //if(!"".equals(subid)&&"".equals(type)){
        //&&("dept".equals(type)||"subcom".equals(type))
        if("v2resourcetree".equals(cmd)&&!"".equals(subid)){
            //结果转json
            log.writeLog("setParam---begin"+newDemo);
            //Object object = JSON.parse(demo);
            JSONObject demojson=JSONObject.parseObject(demo);
            Object object=demojson.get("datas");
            log.writeLog("setParam---object"+object.toString());
            if (object instanceof JSONObject) {


                if(demojson!=null&&demojson.size()>0){
                    JSONObject datas=demojson.getJSONObject("datas");

                    JSONArray children=datas.getJSONArray("children");
                    JSONArray newchildren=new JSONArray();
                    if(children!=null&&children.size()>0){
                        for(int i=0;i<children.size();i++){
                            JSONObject obj= children.getJSONObject(i);
                            String type1=obj.getString("type");//
                            if("dept".equals(type1)){//部门
                                //判断当前部门的分部是不是属于 条件的分部  或者部门分部的上级分部
                                if(checkdep(obj.getString("id"),subid)){
                                    newchildren.add(obj);
                                }
                            }else if("subcom".equals(type1)){//分部
                                if(checkSub(obj.getString("id"),subid)){
                                    newchildren.add(obj);
                                }
                            }else{
                                newchildren.add(obj);
                            }

                        }
                        datas.put("children", newchildren);
                        newDemo=demojson.toJSONString();
                    }else{
                       String type1=datas.getString("type");
                       if("resource".equals(type1)){
                           newDemo=demojson.toJSONString();
                       }
                        //datas.put("children", newchildren);

                    }
                    //存在单独为人员的情况

                    //demojson.put("datas",newchildren);


                }
            } else if (object instanceof JSONArray) {
                log.writeLog("JSONArray");

                if(demojson!=null&&demojson.size()>0){
                    //JSONObject datas=demojson.getJSONObject("datas");
                    JSONArray children=demojson.getJSONArray("datas");
                    JSONArray newchildren=new JSONArray();
                    if(children!=null&&children.size()>0){
                        for(int i=0;i<children.size();i++){
                            JSONObject obj= children.getJSONObject(i);
                            String type1=obj.getString("type");//
                            if("dept".equals(type1)){//部门
                                //判断当前部门的分部是不是属于 条件的分部  或者部门分部的上级分部
                                if(checkdep(obj.getString("id"),subid)){
                                    newchildren.add(obj);
                                }
                            }else if("subcom".equals(type1)){//分部
                                if(checkSub(obj.getString("id"),subid)){
                                    newchildren.add(obj);
                                }
                            }else{
                                newchildren.add(obj);
                            }

                        }
                    }
                    //demojson.put("datas",newchildren);
                    demojson.put("datas", newchildren);
                    newDemo=demojson.toJSONString();

                }
            }

        }
        return  newDemo;
    }
    @WeaReplaceAfter(value = "/api/public/browser/condition/17", order = 1, description = "haha")
    public String setParam3(WeaAfterReplaceParam param){
        Map paraMap=param.getParamMap();
        String demo =param.getData();
        String cmd=Util.null2String(paraMap.get("cmd")).trim() ;
        String subid =Util.null2String(paraMap.get("zcsubid")).trim() ;

        String newDemo=demo;
        //if(!"".equals(subid)&&"".equals(type)){
        //&&("dept".equals(type)||"subcom".equals(type))
        log.writeLog("condition"+subid);
        if(!"".equals(subid)){
            //结果转json
            JSONObject demojson=JSONObject.parseObject(demo);

            if(demojson!=null&&demojson.size()>0){


                JSONArray children=demojson.getJSONArray("conditions");
                JSONArray newchildren=new JSONArray();
                if(children!=null&&children.size()>0){
                    for(int i=0;i<children.size();i++){
                        if(i==3){
                            //browserConditionParam
                            JSONArray replaceDatas =getSub(subid);
                            JSONObject subjson= children.getJSONObject(i);
                            subjson.put("viewAttr",1);
                            if(subjson!=null&&subjson.size()>0){
                                JSONObject browserConditionParam =subjson.getJSONObject("browserConditionParam");
                                if(browserConditionParam!=null&&browserConditionParam.size()>0){
                                    browserConditionParam.put("replaceDatas",replaceDatas);
                                    browserConditionParam.put("viewAttr",1);
                                }
                            }
                        }

                    }
                }


            }
            newDemo=demojson.toJSONString();
        }
        return  newDemo;
    }
    @WeaReplaceAfter(value = "/api/public/browser/condition/1", order = 1, description = "haha")
    public String setParam5(WeaAfterReplaceParam param){
        Map paraMap=param.getParamMap();
        String demo =param.getData();
        String cmd=Util.null2String(paraMap.get("cmd")).trim() ;
        String subid =Util.null2String(paraMap.get("zcsubid")).trim() ;

        String newDemo=demo;
        //if(!"".equals(subid)&&"".equals(type)){
        //&&("dept".equals(type)||"subcom".equals(type))
        log.writeLog("condition5"+subid);
        if(!"".equals(subid)){
            //结果转json
            JSONObject demojson=JSONObject.parseObject(demo);

            if(demojson!=null&&demojson.size()>0){


                JSONArray children=demojson.getJSONArray("conditions");
                JSONArray newchildren=new JSONArray();
                if(children!=null&&children.size()>0){
                    for(int i=0;i<children.size();i++){
                        if(i==3){
                            //browserConditionParam
                            JSONArray replaceDatas =getSub(subid);
                            JSONObject subjson= children.getJSONObject(i);
                            subjson.put("viewAttr",1);
                            if(subjson!=null&&subjson.size()>0){
                                JSONObject browserConditionParam =subjson.getJSONObject("browserConditionParam");
                                if(browserConditionParam!=null&&browserConditionParam.size()>0){
                                    browserConditionParam.put("replaceDatas",replaceDatas);
                                    browserConditionParam.put("viewAttr",1);
                                }
                            }
                        }

                    }
                }


            }
            newDemo=demojson.toJSONString();
        }
        return  newDemo;
    }
    @WeaReplaceAfter(value="/api/cube/search/getList",order=1)
    public String getData(WeaAfterReplaceParam param){
        //String paramMapStr=param.getParamMap().get("customid");
        Map paraMap=param.getParamMap();
        String demo =param.getData();
        String newDemo=demo;
        String var2="";
        if(paraMap!=null&&paraMap.size()>0){
            String customid=(String)paraMap.get("customid");
            if(!"".equals(customid)&&"1".equals(customid)){//判断需要重写的模块
                //String demo =param.getData();
                JSONObject demojson=JSONObject.parseObject(demo);
                if(demojson!=null&&demojson.size()>0){
                    String datas= Util.null2String(demojson.getString("datas")) ;//获取分页的key
                    if(!"".equals(datas)){
                        String var13 = Util_TableMap.getVal(datas);//获取key 字符串
                        // xml 解析
                        String newvar13=SAXxml(var13);
                        //插入新的缓存
                        var2 = Util.null2String(WeaCommon.createGuid());
                        Util_TableMap.setVal(var2, newvar13);
                        JSONObject newdemojson=JSONObject.parseObject(demo);
                        newdemojson.put("datas",var2);
                        newDemo=newdemojson.toJSONString();
                    }

                }
            }
        }


        // System.out.println(paramMapStr);
        return newDemo;
    }
    public String SAXxml(String xml){
        Map<String,String> map=new HashMap<String,String>();
        boolean flag=false;
        String html="";
        StringReader read = new StringReader(xml);
        // 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
        InputSource source = new InputSource(read);
        // 创建一个新的SAXBuilder
        SAXBuilder sb = new SAXBuilder();
        try {
            // 通过输入源构造一个Document
            org.jdom.Document doc = sb.build(source);
            // 取的根元素
            org.jdom.Element root = doc.getRootElement();
            org.jdom.Element operates = root.getChild("operates");
            org.jdom.Element heads = root.getChild("head");
            if(operates!=null){
                org.jdom.Element popedom= operates.getChild("popedom");
                if(popedom!=null){
                    //popedom.setAttribute("transmethod","com.engine.demo.impl.LLFSearchTransMethodProxy.getSearchResultOperation");
                    //popedom.setAttribute("")
                    //popedom.setAttribute("transmethod","com.api.cube.util.CubeSearchTransMethodProxy.getSearchResultOperation");

                }
                if(heads!=null){
                    List<Element> lists=(List<Element>)heads.getChildren("col");
                    for(Element elem:lists){
                        String test=elem.getAttribute("text").getValue();
                        if("operatesshow".equals(test)){
                            //elem.setAttribute("transmethod","com.engine.demo.impl.LLFSearchTransMethodProxy.getSearchResultOperation");
                        }

                    }
                }


                html=doc.toString();
                XMLOutputter outputter=new XMLOutputter();
                html=Util.null2String(outputter.outputString(doc)) ;
                if(!"".equals(html)){
                    if(html.indexOf("table")>-1){
                        html=html.substring(html.indexOf("table")-1);
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return html;
    }
    /*
        对比分部
     */
    public boolean checkdep(String depid,String subid){
        RecordSet re=new RecordSet();
        String sql="select subcompanyid1 from hrmdepartment where id in ("+depid+")";
        re.execute(sql);
        String depsubid="";
        while(re.next()){
            depsubid=Util.null2String(re.getString("subcompanyid1")).trim();
        }
        if("".equals(depsubid)){
            return false;
        }
        String newsql="with Department as " +
                "                 (select *,0 as Level from HrmSubCompany where id in ("+subid+") and isnull(canceled,0)=0 " +
                "                union all select d.*,Department.Level + 1 from Department,HrmSubCompany d where Department.id=d.supsubcomid and isnull(d.canceled,0)=0)  " +
                "                 select * from Department where id= "+depsubid;
        log.writeLog("checkdep---"+newsql);
        re.execute(newsql);
        if(re.next()){
            return true;
        }

        return false;
    }
    /*
        对比分部
     */
    public boolean checkSub(String demosubid,String subid){
        RecordSet re=new RecordSet();
        RecordSet re2=new RecordSet();

        String newsql="with Department as " +
                "                 (select *,0 as Level from HrmSubCompany where id in ("+subid+") and isnull(canceled,0)=0 " +
                "                union all select d.*,Department.Level + 1 from Department,HrmSubCompany d where Department.id=d.supsubcomid and isnull(d.canceled,0)=0)  " +
                "                 select * from Department where id= "+demosubid;
        String newsql2=        " with Department as " +
                "                 (select *,0 as Level from HrmSubCompany where id in ("+subid+") and isnull(canceled,0)=0 " +
                "                union all select d.*,Department.Level + 1 from Department,HrmSubCompany d where d.id=Department.supsubcomid and isnull(d.canceled,0)=0)  " +
                "                 select * from Department where id= "+demosubid;
        log.writeLog("setParam---newsql"+newsql);
        log.writeLog("setParam---newsql2"+newsql2);
        re.execute(newsql);
        re2.execute(newsql2);
        if(re.next()){
            return true;
        }else if(re2.next()){
            return true;
        }

        return false;
    }
    /*
        获取分部的 名称
     */
    public  JSONArray getSub(String subid){
        JSONArray jsons=new JSONArray();
        JSONObject json=new JSONObject();
        subid=Util.null2String(subid).trim();
        if("".equals(subid)){
            return jsons;
        }
        String sql="select id,SubCompanyname from HrmSubCompany where id in ("+subid+")";
        RecordSet re=new RecordSet();
        re.execute(sql);
        while(re.next()){
            json=new JSONObject();
            String id=Util.null2String(re.getString("id"));
            String SubCompanyname=Util.null2String(re.getString("SubCompanyname"));
            json.put("id",id);
            json.put("name",SubCompanyname);
            jsons.add(json);
        }
        return jsons;
    }
}
